<template>
    <div>
        <el-dialog :title="editTitle" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="头像" prop="header">
                            <el-upload class="avatar-uploader" :action="fileUploadAction" :show-file-list="false"
                                       :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                                <img v-if="userForm.header" :src="fileDownloadAction+userForm.header" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="性别" prop="sex">
                            <el-radio v-model="userForm.sex" label="false">男</el-radio>
                            <el-radio v-model="userForm.sex" label="true">女</el-radio>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="用户名" prop="name">
                    <el-input v-model="userForm.name"></el-input>
                </el-form-item>
                <el-form-item label="登录名" prop="loginName">
                    <el-input v-model="userForm.loginName"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email"></el-input>
                </el-form-item>
                <el-form-item label="用户组" prop="roleId">
                    <el-select v-model="selectedGroupId" multiple placeholder="请选择">
                        <el-option v-for="item in userGroupList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select v-model="selectedRoleId" multiple placeholder="请选择">
                        <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!--  <el-form-item label="密码" prop="password">
                      <el-input v-model="userForm.password" type="password" readonly></el-input>
                  </el-form-item>-->
                <el-form-item label="状态" prop="status">
                    <el-radio v-model="userForm.status" :label="1">启用</el-radio>
                    <el-radio v-model="userForm.status" :label="0">禁用</el-radio>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm('userForm')"
                           icon="el-icon-document-checked"
                           :loading="loading">确 定</el-button>
                <el-button size="small" type="info" @click="resetForm('userForm')"
                           icon="el-icon-refresh-left">重 置</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "UserEdit",
        props: {
            editTitle: {
                type: String,
                default: "提示信息"
            },
            dialogVisible: {
                type: Boolean,
                required: true
            },
            rowData: {
                type: Object,
                required: false
            }
        },
        watch: {
            rowData: function (newVal, oldVal) {
                if (newVal && newVal.id) {
                    this.queryDataById(newVal.id);
                } else {
                    this.userForm.id = null;
                }
            }
        },
        data() {
            return {
                loading: false,
                roleList: [],
                //选中的roleId
                selectedRoleId: [],
                //用户组
                userGroupList: [],
                //选中的groupId
                selectedGroupId: [],
                fileUploadAction: this.$commonUrlHttp + "api/rest/file/upload?path=user_head",
                fileDownloadAction: this.$commonUrlHttp + "api/rest/file/download/",
                userForm: {
                    id: '',
                    name: '',
                    loginName: '',
                    email: '',
                    roleId: '',
                    password: '1',
                    header: '',
                    sex: "false",
                    status: 1
                },
                rules: {
                    name: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        // {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                    ],
                    loginName: [
                        {required: true, message: '请输入登录名', trigger: 'blur'},
                        // {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                    ],
                    password: [{required: true, message: '请输入密码', trigger: 'blur'}]
                }
            }
        },
        methods: {
            //上传成功
            handleAvatarSuccess(res, file) {
                if (res.code === 200) {
                    this.userForm.header = res.data.code
                }
            },
            //上传之前
            beforeAvatarUpload(file) {
                const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png');
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$errorMsg('上传头像图片只能是 JPG 或者 PNG 格式!');
                }
                if (!isLt2M) {
                    this.$errorMsg('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            handleClose() {
                this.resetForm('userForm');
                this.$emit("callBackFromSub", false);
            },
            submitForm(formName) {
                this.loading = true;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        delete this.userForm.addTime;
                        delete this.userForm.updateTime;
                        this.userForm.roleId = this.selectedRoleId ? this.selectedRoleId.join(",") : '';
                        this.userForm.groupId = this.selectedGroupId ? this.selectedGroupId.join(",") : '';
                        if (this.userForm.id) {
                            this.$httpPut(this.$axiosBaseHttp, "api/rest/userInfo/upd", this.userForm).then(res => {
                                if (res.code === 200) {
                                    this.resetForm('userForm');
                                    this.$emit("callBackFromSub", false);
                                    this.$successMsg(this.editTitle + "成功");
                                } else {
                                    this.$errorMsg(this.editTitle + "失败");
                                }
                                this.loading = false;
                            });
                        } else {
                            this.userForm.signName = '无个性签名';
                            this.$httpPost(this.$axiosBaseHttp, "api/rest/userInfo/save", this.userForm).then(res => {
                                if (res.code === 200) {
                                    this.resetForm('userForm');
                                    this.$emit("callBackFromSub", false);
                                    this.$successMsg(this.editTitle + "成功");
                                } else {
                                    this.$errorMsg(this.editTitle + "失败");
                                }
                                this.loading = false;
                            });
                        }
                    } else {
                        this.loading = false;
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            queryDataById(id) {
                this.$httpGet(this.$axiosBaseHttp, "api/rest/userInfo/one", {id: id}).then(res => {
                    if (res.code === 200) {
                        this.userForm = res.data;
                        this.selectedRoleId = this.userForm.roleId ? this.userForm.roleId.split(",") : [];
                        this.selectedGroupId = this.userForm.groupId ? this.userForm.groupId.split(",") : [];
                    }
                });
            },
            //初始化角色选择器
            initRoleSelect() {
                this.$httpGet(this.$axiosBaseHttp, "api/rest/roleInfo/list", {}).then(res => {
                    if (res.code === 200) {
                        this.roleList = res.data;
                    }
                })
            },
            //初始化用户组选择器
            initUserGroupSelect() {
                this.$httpGet(this.$axiosBaseHttp, "api/rest/userGroupInfo/list", {}).then(res => {
                    if (res.code === 200) {
                        this.userGroupList = res.data;
                    }
                })
            }
        },
        mounted() {
            this.initRoleSelect();
            this.initUserGroupSelect();
        }
    }
</script>

<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 16px;
        color: #8c939d;
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
    }

    .avatar {
        width: 50px;
        height: 50px;
        display: block;
        border-radius: 50px;
    }

    .el-select {
        width: 100%;
    }
</style>
